<template>
  
  <div class="page-row">
    
    <!-- 左上地图区域 -->
    <div class="map-section">
          <dv-border-box8 class="map-content">
            <Map class="map" />
          </dv-border-box8>
        </div>
    <!-- 视频区 -->
    <div class="video-container">
      <video controls>
        <source src="https://water.tju.edu.kg/source/1.mp4" type="video/mp4">
        </video>
      <video controls>
        <source src="https://water.tju.edu.kg/source/2.mp4" type="video/mp4">
      </video>
    </div>

    <div class="work-panel">
    <!-- 选择面板 -->
    <div class="selector-container">
      <label>
        图表类型：
        <select v-model="chartType" @change="updateChart">
          <option value="lineChart">水质状态图</option>
          <option value="barChart">水质对比图</option>
        </select>
      </label>

      <label v-show="isBar">
        水质特征：
        <select v-model="feature" @change="updateChart">
          <option v-for="(label, key) in featureLabels" :key="key" :value="key">
            {{ label }}
          </option>
        </select>
      </label>

      <label v-show="isLine">
        断面选择：
        <select v-model="sectionId" @change="updateChart">
          <option v-for="(name, id) in sectionMap" :key="id" :value="id">{{ name }}</option>
        </select>
      </label>

      <label>
        日期选择：
        <input
          type="date"
          v-model="date"
          :min="minDate"
          :max="maxDate"
          @change="updateChart"
        />
      </label>
    </div>
    <!-- 图表区 -->
    <div id="chartContainer">
      <!-- 折线图 -->
      <div
        id="smallChartsContainer"
        v-show="isLine"
        ref="smallContainer"
      >
        <div id="chart1"></div>
        <div id="chart2"></div>
        <div id="chart3"></div>
        <div id="chart4"></div>
      </div>

      <!-- 柱状图 -->
      <div
        id="barChart"
        v-show="isBar"
        ref="barChartEl"
        style="width: 100%; height: 100%"
      ></div>
    </div>
    </div>
  </div>
  
</template>

<script setup>
import { ref, reactive, computed, onMounted } from 'vue'
import axios from 'axios'
import * as echarts from 'echarts'
import Map from '@/components/Map.vue'


const sectionMap = reactive({
  1: '塘汉公路桥断面',
  2: '三岔口断面',
  3: '海河大闸断面',
  4: '蓟运河防潮闸断面',
  5: '万家码头断面',
  6: '大红桥断面',
  8: '北洋桥断面',
  9: '土门楼断面',
  10: '大套桥断面',
  11: '青静黄防潮闸断面',
  12: '北排水河防潮闸断面'
})

const featureLabels = reactive({
  ph: 'pH值',
  total_phosphorus: '总磷',
  total_nitrogen: '总氮',
  ammonia_nitrogen: '氨氮',
  temperature: '温度',
  dissolved_oxygen: '溶解氧',
  conductivity: '电导率',
  ntu: '浊度',
  permanganate_index: '高锰酸钾指数'
})

const chartType  = ref('lineChart')
const feature    = ref('ph')
const sectionId  = ref(1)

const today  = new Date()
const yyyy   = today.getFullYear()
const mm     = String(today.getMonth() + 1).padStart(2, '0')
const dd     = String(today.getDate()).padStart(2, '0')
const maxDate = `${yyyy}-${mm}-${dd}`
const minDate = '2025-03-25'
const date   = ref(maxDate)

const isBar  = computed(() => chartType.value === 'barChart')
const isLine = computed(() => chartType.value === 'lineChart')

const barChartEl = ref(null)
let barChartInstance = null
let smallChartInstances = [] 

//折线柱状图渲染
function fetchBarChartData () {
  if (!date.value) return
  axios.get('http://47.93.46.0:8081/water_quality/barchart', {
    params: { data_date: date.value }
  }).then(({ data: res }) => {
    const rows = res.data || []
    const ids  = Object.keys(sectionMap).map(Number)
    const names  = Object.values(sectionMap)
    const values = ids.map(id => {
      const item = rows.find(d => d.section_id === id)
      return item ? Number(item[feature.value]) : null
    })

    barChartInstance.setOption({
      title  : { text: '水质对比图', left: 'center' },
      tooltip: { trigger: 'axis', axisPointer: { type: 'shadow' } },
      grid   : { left: '5%', right: '5%', bottom: '10%', containLabel: true },
      xAxis  : { type: 'category', data: names, axisLabel: { rotate: -30 } },
      yAxis  : { type: 'value', min: 0, name: featureLabels[feature.value] },
      series : [{
        name : featureLabels[feature.value],
        type : 'bar',
        data : values,
        label: { show: true, position: 'top', formatter: p => p.value == null ? '无数据' : p.value.toFixed(2) }
      }]
    })
    barChartInstance.resize()
  })
}

function fetchLineChartData () {
  if (!date.value) return
  axios.get('http://47.93.46.0:8081/water_quality/linechart', {
    params: { section_id: sectionId.value, data_date: date.value }
  }).then(({ data: res }) => {
    const data  = res.data || []
    const dates = data.map(d => d.data_date)

    const seriesArr = [
      { name: 'pH值', key: 'ph' },
      { name: '总磷', key: 'total_phosphorus' },
      { name: '总氮', key: 'total_nitrogen' },
      { name: '氨氮', key: 'ammonia_nitrogen' }
    ]

    smallChartInstances.forEach((chart, i) => {
      const { name, key } = seriesArr[i]
      chart.setOption({
        title : { text: name, left: 'center', top: '5%' },
        tooltip: { trigger: 'axis' },
        xAxis : { type: 'category', data: dates },
        yAxis : { type: 'value', min: 0 },
        series: [{ type: 'line', data: data.map(d => d[key]), smooth: true }]
      })
      chart.resize()
    })
  })
}

function updateChart () {
  if (isBar.value) {
    fetchBarChartData()
  } else {
    fetchLineChartData()
  }
}

onMounted(() => {
  
  barChartInstance = echarts.init(barChartEl.value)

  smallChartInstances = [
    echarts.init(document.getElementById('chart1')),
    echarts.init(document.getElementById('chart2')),
    echarts.init(document.getElementById('chart3')),
    echarts.init(document.getElementById('chart4'))
  ]

  // 设定日期 input 限制
  updateChart()

  window.addEventListener('resize', () => {
    barChartInstance.resize()
    smallChartInstances.forEach(c => c.resize())
  })
})
</script>

<style scoped lang="scss">

#chartContainer{
  flex:1;                    
  background:#0d1222;
  padding:10px;
  box-sizing:border-box;
  overflow:hidden;
  border-radius: 12px;        
}
#smallChartsContainer {
  display: flex;
  flex-wrap: wrap;
  width: 100%;
  height: 100%;
}
#smallChartsContainer > div {
  width: 50%;
  height: 50%;
}
.page-row{
  position:absolute;
  top:70px; left:0; right:0;
  bottom:60px;     
  display:flex;
  overflow:hidden;
}
.map-section {
        flex: 1;
        margin: 0 10px;
        position: relative;
        height: 65%;
        display: flex;
        flex-direction: column;
        justify-content: stretch;

        :deep(.dv-border-box8) {
            width: 100%;
            height: 100%;
            
            .border-box-content {
                width: 100%;
                height: 100%;
                padding: 30px;
                box-sizing: border-box;
                display: flex;
                flex-direction: column;
                background: unset !important;
                border-radius: unset !important;
                backdrop-filter: unset !important;
            }
        }

        .map-content {
            width: 100%;
            height: 100%;
            position: relative;
            overflow: hidden;
            border-radius: 4px;
        }
    }

.work-panel{
  flex:1;                
  display:flex;
  flex-direction:column; 
}
.selector-container{
  padding:10px 20px;
  background:#2058c7;
  border-radius:0 0 0 8px;
  border-radius: 12px;
}
.selector-container label {
  font-family: Arial, sans-serif;
  font-size: 14px;
  color: #333;
  
}
.selector-container select,
.selector-container input[type='date'] {
  padding: 5px 10px;
  font-size: 14px;
  border: 1px solid #2058c7;
  border-radius: 6px;
  outline: none;
  box-shadow: 0 1px 3px rgba(0, 0, 0, 0.1);
  background-color: #fff;
  transition: border 0.3s ease;
}
.selector-container select:focus,
.selector-container input[type='date']:focus {
  border-color: #409eff;
  box-shadow: 0 0 3px rgba(64, 158, 255, 0.6);
}

.video-container {
  position: absolute;
  bottom: 10px; /* 距离底部的距离 */
  left: 10px; /* 距离左侧的距离 */
  display: flex;
  flex-direction: row;
  gap: 10px; /* 视频之间的间距 */
}

video {
  width: 500px; /* 或者设定固定宽度 */
  max-width: 370px; /* 最大宽度 */
}
</style>

